package com.xjcs.saplingplan.ui.fragment

import android.annotation.SuppressLint
import android.os.Bundle
import androidx.fragment.app.viewModels
import com.blankj.utilcode.util.GsonUtils
import com.jeremyliao.liveeventbus.LiveEventBus
import com.xjcs.saplingplan.adapter.CountdownAdapter
import com.xjcs.saplingplan.base.BaseVbFragment
import com.xjcs.saplingplan.const.EventBusConstants
import com.xjcs.saplingplan.databinding.FragmentCountdownListBinding
import com.xjcs.saplingplan.datastore.AppData
import com.xjcs.saplingplan.room.bean.countdown.CountdownBean
import com.xjcs.saplingplan.ui.viewmodel.CountdownViewModel

class CountdownListFragment: BaseVbFragment<FragmentCountdownListBinding>() {

    companion object {
        fun getInstance(type: Int): CountdownListFragment {
            val fragment = CountdownListFragment()
            val bundle = Bundle().apply {
                putInt("type", type)
            }
            fragment.arguments = bundle
            return fragment
        }
    }

    override fun getViewBinding(): FragmentCountdownListBinding {
        return FragmentCountdownListBinding.inflate(layoutInflater)
    }

    private var countdownAdapter: CountdownAdapter? = null
    private val mViewModel: CountdownViewModel by viewModels()
    private val userId = AppData.getUserId()
    private val cateName = ""

    private var countdownList = mutableListOf<CountdownBean>()

    override fun initUi() {
        initView()
        initRecyclerView()
        getData()
    }

    private fun initView() {
    }

    override fun initListener() {
    }

    private fun initRecyclerView() {
        countdownAdapter = CountdownAdapter(requireContext(), countdownList)
        mBinding.recyclerView.adapter = countdownAdapter
    }

    private fun getData() {
        mViewModel.getCountdownList(userId, cateName)
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun registerObserver() {
        //刷新列表
        LiveEventBus.get<String>(EventBusConstants.REFRESH_COUNTDOWN_LIST).observe(this){
            mViewModel.getCountdownList(userId, cateName)
        }
        //数据列表
        mViewModel.countdownList.observe(this){
            countdownList = it
            countdownAdapter?.notifyDataSetChanged()
        }
    }

}